import { Toast, MessageBox } from "mint-ui";
const state = {
  // count: 0,
  cartList: JSON.parse(localStorage.getItem("cart") || "[]"),
};

const mutations = {
  NUM_CLICK(state, obj) {
    state.cartList.forEach((item) => {
      if (item.shop_id === obj.shop_id) {
        item.count = obj.count;
        localStorage.setItem("cart", JSON.stringify(state.cartList));
      }
    });
  },

  SET_CART(state, goodslist) {
    let flag = false;

    state.cartList.some((item) => {
      // console.log(goodslist.shop_id);
      // console.log(item.shop_id);
      if (item.shop_id == goodslist.shop_id) {
        item.count += goodslist.count;
        flag = true;
      }
    });
    if (!flag) {
      state.cartList.push(goodslist);
    }
    localStorage.setItem("cart", JSON.stringify(state.cartList));
  },

  CHECKED_ALL(state) {
    let flags = state.cartList.every((item) => item.flag);
    // console.log(flag);
    if (flags) {
      state.cartList.forEach((item) => {
        item.flag = false;
      });
    } else {
      state.cartList.forEach((item) => {
        item.flag = true;
      });
    }
  },

  DEL_CARTS(state, index) {
    MessageBox({
      title: "提示",
      message: "是否删除" + "?",
      showCancelButton: true,
    }).then((res) => {
      // console.log(res);
      if (res == "confirm") {
        state.cartList.splice(index, 1);
        localStorage.setItem("cart", JSON.stringify(state.cartList));
        Toast({
          message: "删除成功",
          duration: 1500,
        });
      }
    });
  },
};

const actions = {};

const getters = {
  getAllCount(state) {
    let c = 0;
    let user = JSON.parse(sessionStorage.getItem("user") || "{}");
    if (!user.name) {
      return (c = 0);
    }
    state.cartList.forEach((item) => {
      c += item.count;
    });
    return c;
  },
  getAllPrice(state) {
    let p = 0;
    state.cartList.forEach((item) => {
      if (item.flag) {
        p += item.count * item.price;
      }
    });
    return p;
  },
  checkedAll(state) {
    return state.cartList.every((item) => item.flag);
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters,
};
